package com.cdtu.service;

import com.cdtu.dao.CodeDao;
import com.cdtu.model.pojo.Code;
import com.cdtu.utils.UUIDUtil;
import com.cdtu.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CodeService {

    @Autowired
    private CodeDao codeDao;

    @Autowired
    private UUIDUtil uuidUtil;

    @Autowired
    private DateUtil dateUtil;

    /**
     * 生成激活码
     *
     * @return
     */
    public Code generateCode() {
        Code code = new Code();
        code.setState(0);
        code.setId(uuidUtil.generateUUID().toUpperCase());
        code.setCreateTime(dateUtil.getCurrentDate());
        codeDao.saveCode(code);
        return code;
    }

    /**
     * 删除激活码
     *
     * @param codeId
     */
    public void deleteCodeById(String codeId) {
        //判断是否使用
        if (codeDao.findCodeById(codeId).getState() == 1) {
            throw new RuntimeException("已被使用,无法删除");
        }
        codeDao.deleteCodeById(codeId);
    }

    /**
     * 获取激活码记录条数
     *
     * @return
     */
    public Long getCodeCount() {
        return codeDao.getCodeCount();
    }

    public List<Code> findCode(Integer page, Integer showCount) {
        return codeDao.findCode((page - 1) * showCount, showCount);
    }
}
